package com.myhome.util;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	private static ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * 将对象序列化
	 * 
	 * @param obj
	 * @return
	 */
	public static String getJsonFromObject(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 反序列化对象字符串
	 * 
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T getObjectFromJson(String json, Class<T> clazz) {
		try {
			return objectMapper.readValue(json, clazz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 反序列化字符串成为对象
	 * 
	 * @param json
	 * @param valueTypeRef
	 * @return
	 */
	public static <T> T getObjectFromJson(String json, TypeReference<T> valueTypeRef) {
		try {
			return objectMapper.readValue(json, valueTypeRef);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) throws ParseException, IOException {
		// 初始化一个对象，一个数组
		TestObject user = new TestObject();
		user.setName("小民");
		user.setEmail("xiaomin@sina.com");
		user.setAge(20);
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		user.setBirthday(dateformat.parse("1996-10-01"));
		String str = getJsonFromObject(user);

		System.out.println(str);

		List<TestObject> users = new ArrayList<TestObject>();
		users.add(user);
		user.setName("小民111");
		user.setEmail("xiaomin22@sina.com");
		user.setAge(12);
		users.add(user);
		String strArr = getJsonFromObject(users);

		System.out.println(strArr);
		
		String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"mail\":\"xiao111min@sina.com\"}";  
		TestObject user1 = getObjectFromJson(json,TestObject.class);
		System.out.println(user1.getEmail());
		
	}
}
